<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

defined('_JEXEC') or die( 'Restricted access' );

jimport( 'joomla.application.component.model' );

class JAJobBoardModelJAFeeds extends JModel
{

	var $_data = null;
	var $_sdata = null;
	var $_total = null;
	var $_pagination = null;
	var $_id = null;	
	var $_sections;
	var $_exCategories;
	var $_seccatlist;
	var $_table;
	
	function __construct()
	{
		parent::__construct();

		global $mainframe, $option;

		// Get the pagination request variables
		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart	= $mainframe->getUserStateFromRequest( $option.'.limitstart', 'limitstart', 0, 'int' );

		// In case limit has been changed, adjust limitstart accordingly
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
		
		//edit feed
		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
	}
	
	
	/**
    * Get email table instance
    * @return JTable Email table object
    */
    function &_getTable(){
        if($this->_table == null){
        	$this->_table = &JTable::getInstance('JA_Feeds', 'JobBoardTable');
		}
		return $this->_table;
	}
	
		/**
	* Get email item by ID
	* @return Email Table object
	*/
	function getItem(){
		static $item;
		if (isset($item)) {
			return $item;
		}

		$table =& $this->_getTable();

		// Load the current item if it has been defined
		$edit	= JRequest::getVar('edit',true);
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger($cid, array(0));
		
		if ($edit) {
			$table->load($cid[0]);
		}
		return $table;	    
	}
	
	function setId($id)
	{
		// Set id and wipe data
		$this->_id		= $id;
		$this->_sdata	= null;
	}
	/**
	 * Method to get the total number of feeds items
	 *
	 * @access public
	 * @return integer
	 */
	function getTotal()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}		
		return $this->_total;
	}

	/**
	 * Method to get a pagination object for the feeds
	 *
	 * @access public
	 * @return integer
	 */
	function getPagination()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
			
		}
		
		return $this->_pagination;
	}
	
	

	function getItems(){
		global $mainframe, $option;
		
	    $limit				= $mainframe->getUserStateFromRequest( 'global.list.limit',	'limit',$mainframe->getCfg( 'list_limit' ),	'int' );
		$limitstart			= $mainframe->getUserStateFromRequest( $option.'.feeds.limitstart','limitstart',0,	'int' );
		
		$db = &JFactory::getDBO();
		if (JRequest::getVar('tab','feedlist')=='feedlist')
			$where_more = " AND f.is_user=0";
		else 
			$where_more = " AND f.is_user=1";
		$query = $this->_buildQuery($where_more);
		$db->setQuery($query);
		//print_r($db->getQuery($query));exit;
		$items = $db->loadObjectList();
		for ($i=0;$i<count($items);$i++)
		{
			$items[$i]->feed_name = JFilterInput::_decode($items[$i]->feed_name);
			$items[$i]->feed_name = JFilterInput::clean($items[$i]->feed_name);
			$items[$i]->feed_alias = JFilterInput::_decode($items[$i]->feed_alias);
			$items[$i]->feed_alias = JFilterInput::clean($items[$i]->feed_alias);
			$items[$i]->feed_description = JFilterInput::_decode($items[$i]->feed_description);
		}
		$total = count( $items );

		jimport('joomla.html.pagination');
		$this->_pagination = new JPagination( $total, $limitstart, $limit );
		
		// slice out elements based on limits
		$list = array();
		if (is_array($items))
			$list = array_slice( $items, $this->_pagination->limitstart, $this->_pagination->limit );
		
		return $list;
	}
	
	function _buildQuery($where_more = '', $limit = 0, $limitstart = 0)
	{
    	global $mainframe, $option;
    	$db =& JFactory::getDBO();
    	$option_1 = $option.'jafeeds';
    	$search				= $mainframe->getUserStateFromRequest( $option_1.'.feeds.search',              'search',           '',         'string' );
		$filter_order		= $mainframe->getUserStateFromRequest( $option_1.'.feeds.filter_order',		'filter_order',		'f.feed_name',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option_1.'.feeds.filter_order_Dir',	'filter_order_Dir',	'ASC',	'word' );
		$filter_state		= $mainframe->getUserStateFromRequest( $option_1.'.filter_state', 'filter_state', '',	'word' );
		
		$search				= JString::strtolower( $search );
		$orderby	= ' ORDER BY '. $filter_order .' '. $filter_order_Dir;
    	$where = ' WHERE 1=1 ';
    	if($search){
    		$where = " AND LOWER(value) like ".$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
    	}
    	if ($where_more!='')
    		$where .= $where_more;
    	if ( $filter_state )
		{
			if ( $filter_state == 'P' ) {
				$where .= ' AND f.published = 1';
			} else if ($filter_state == 'U' ) {
				$where .= ' AND f.published = 0';
			}
		}
        $query = "SELECT   * ".
				 "FROM 	`#__ja_feeds` as f ".
				 $where.
				 $orderby;

        return $query;
	}

	function getData()
	{
		// Load the data
		if (empty( $this->_data )) {
			$query = $this->_buildQuery();
			$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));;
		}
		if (!$this->_data) {
			$this->_data = null;
		}
		
		return $this->_data;
	}

	
//Feed
	
	/**
	 * Method to remove a feed
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.5
	 * lvh
	 */
	function delete($cid = array())
	{
		$result = false;

		if (count( $cid ))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
			$query = 'DELETE FROM `#__ja_feeds`'
				. ' WHERE id IN ( '.$cids.' )';
			$this->_db->setQuery( $query );
			if(!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}

	/**
	 * Method to (un)publish a feed
	 *
	 * @access	public
	 * @return	boolean	True on success
	 * @since	1.5
	 * lvh
	 */
	function publish($cid = array(), $publish = 1)
	{
		$user 	=& JFactory::getUser();

		if (count( $cid ))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
			
			$query = "UPDATE `#__ja_feeds` SET published='$publish'"
	. "\nWHERE id IN ($cids)";
	
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}
	
	function store()
	{
		$db		=& JFactory::getDBO();
		$row	=& $this->getItem();
		$post    = JRequest::get('request', JREQUEST_ALLOWHTML);
		if (is_array($post['filter_cat_id']))
			$post['filter_cat_id'] = implode(',',$post['filter_cat_id']);
		if (is_array($post['filter_location_id']))
			$post['filter_location_id'] = implode(',',$post['filter_location_id']);
		if (!$row->bind( $post )) {
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return JText::_("Bind data false");
		}

		if ($row->check() != 'SUCCESS')
		{
//			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return false;
		}

		if (!$row->store())
		{
			echo "<script> alert('".$row->getError(true)."'); window.history.go(-1); </script>\n";
			return JText::_('Store fail');
			//return false;
		}
		return $row->id;
	}
	
	function getDefaultData()
	{
//		$jbconfig =& $this->getInstance('config','jaModel');
//		return $jbconfig->getData();
	}

}
